﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using UTSDAL.LINQSQL.Model;
using UTSDAL.LINQSQL.DAO;
using log4net;
using System.Text;
using UTSDAL.LINQSQL.Views;
using UTS.Controls;

public partial class pages_admin_reservation : System.Web.UI.Page
{
    private static readonly ILog log = LogManager.GetLogger(typeof(pages_admin_reservation));

    private List<Semester> semesterList = null;

    private SemesterDAO semesterDAO = new SemesterDAO();

    private Semester selectedSemester = null;

    private TimetableEventDAO timetableEventDAO = new TimetableEventDAO();

    private List<ReservationView> timetableEvents = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        // Getting current Semester as per current date
        this.selectedSemester = semesterDAO.getCurrentSemester();

        semesterList = semesterDAO.selectAll();
        SemesterListDropDown.DataSource = semesterList;
        SemesterListDropDown.DataBind();

        // Setting Current Semester as Default value to be displayed
        SemesterListDropDown.SelectedValue = selectedSemester.SemesterId.ToString();

        timetableEvents = timetableEventDAO.getAllReservationViews(selectedSemester);
        ReservationGridView.DataSource = timetableEvents;
        ReservationGridView.DataBind();
    }


    private ReservationView selectedTimetableEvent = null;

    protected void ReservationEdit(object sender, EventArgs e)
    {
        LinkButton EditLinkButtonControl = (LinkButton)sender;

        String reservationViewId = EditLinkButtonControl.CommandArgument.ToString();



        var reservationEventVar = from r in timetableEvents
                                  where r.ReservationViewId.Equals(reservationViewId)
                                  select r;

        selectedTimetableEvent = reservationEventVar.SingleOrDefault<ReservationView>();
        List<ReservationView> views = new List<ReservationView>();
        views.Add(selectedTimetableEvent);
        ReservationDetailsView.DefaultMode = DetailsViewMode.Edit;
        ReservationDetailsView.DataSource = views;
        ReservationDetailsView.DataBind();
        


        ReservationEditingPanel.Visible = true;
        ReservationViewPanel.Visible = false;
                    

    }


    protected void ReservationGridView_RowCreated(object sender, GridViewRowEventArgs e)
    {
        log.Debug("Row Created");
        ReservationView reservationView = (ReservationView)e.Row.DataItem;

        if (reservationView != null)
        {
            log.Debug("Setting Cohort & Module");
            Literal CohortLiteralControl = (Literal)e.Row.FindControl("Cohort");
            CohortLiteralControl.Text = reservationView.Cohort.CohortName;

            Literal ModuleLiteralControl = (Literal)e.Row.FindControl("Module");
            ModuleLiteralControl.Text = reservationView.Module.ModuleName;

            GridView ModuleEventReservationGridControl = (GridView)e.Row.FindControl("ModuleEventReservationGrid");

            StringBuilder builder = new StringBuilder();

            builder.Append("<table cellspacing='5px' cellpadding='5px' border='0'>");
            foreach (TimetableEvent reservedEvent in reservationView.ReservedEvent)
            {
                builder.Append("<tr>");
                builder.Append("<td>");
                builder.Append(reservedEvent.ModuleEvent.ModuleEventType.ModuleEventTypeName);
                builder.Append("</td>");
                builder.Append("<td>");
                builder.Append(reservedEvent.CourseDay.CourseDayName);
                builder.Append("</td>");
                builder.Append("<td>");
                builder.Append(TimeUtils.convertTimespan(reservedEvent.StartTime));
                builder.Append(" - ");
                builder.Append(TimeUtils.convertTimespan(reservedEvent.EndTime));
                builder.Append("</td>");

                builder.Append("</tr>");
            }
            builder.Append("</table>");



            Literal ModuleEventInfoLiteralControl = (Literal)e.Row.FindControl("ModuleEventInfo");
            ModuleEventInfoLiteralControl.Text = builder.ToString();

        }
    }


    

    protected void ReservationNew(object sender, EventArgs e)
    {
        ReservationViewPanel.Visible = false;
        ReservationEditingPanel.Visible = true;

        List<ReservationView> views = new List<ReservationView>();
        views.Add(new ReservationView());

        ReservationDetailsView.DefaultMode = DetailsViewMode.Insert;
        ReservationDetailsView.DataSource = views;
        ReservationDetailsView.DataBind();
        

    }


    protected void ReservationDetailsView_DataBound(object sender, EventArgs e)
    {
        CohortDropDownList Reservation_CohortDropDownList = (CohortDropDownList)ReservationDetailsView.FindControl("Reservation_CohortDropDownList");
        SemesterDropDownList Reservation_SemesterDropDownList = (SemesterDropDownList)ReservationDetailsView.FindControl("Reservation_SemesterDropDownList");
        ModuleDropDownList Reservation_ModuleDropDownList = (ModuleDropDownList)ReservationDetailsView.FindControl("Reservation_ModuleDropDownList");
        LecturerDropDownList Reservation_LecturerDropDownList = (LecturerDropDownList)ReservationDetailsView.FindControl("Reservation_LecturerDropDownList");

        Reservation_CohortDropDownList.reload();
        Reservation_ModuleDropDownList.reload();
        Reservation_SemesterDropDownList.reload();
        Reservation_LecturerDropDownList.reload();

        if (ReservationDetailsView.DefaultMode.Equals(DetailsViewMode.Edit))
        {
            TimetableEvent reservationEventToEdit = selectedTimetableEvent.ReservedEvent.SingleOrDefault<TimetableEvent>();
            log.Debug("Editing Reservation " + reservationEventToEdit.TimetableEventId);
            log.Debug(reservationEventToEdit.Cohort);
            Reservation_CohortDropDownList.Cohort = reservationEventToEdit.Cohort;
            Reservation_ModuleDropDownList.Module = reservationEventToEdit.Module;
            Reservation_SemesterDropDownList.Semester = reservationEventToEdit.Semester;
            // Lecturer !!

            LoadClassEventsForModule(reservationEventToEdit.Module);
        }
        else if (ReservationDetailsView.DefaultMode.Equals(DetailsViewMode.Insert))
        {

        }

        

    }

    protected void ReservationDelete(object sender, EventArgs e)
    {
        LinkButton DeleteButton = (LinkButton)sender;

        String objectToDeleteId = DeleteButton.CommandArgument.ToString();

        var selectedTimetableEventVar = from timetableEvent in timetableEvents
                                        where timetableEvent.ReservationViewId.Equals(objectToDeleteId)
                                        select timetableEvent;

        ReservationView view = selectedTimetableEventVar.Single<ReservationView>();

        foreach (TimetableEvent timetableEvent in view.ReservedEvent)
        {
            timetableEventDAO.remove(timetableEvent);
        }
    }



    /**
     * 
     * EDITING METHODS
     * 
     */

    private List<TimetableEvent> moduleEvents = null;

    private void LoadClassEventsForModule(Module module)
    {
        moduleEvents = timetableEventDAO.findTimetableEventsForModule(module);
        Repeater ClassEventRepeater = (Repeater)ReservationDetailsView.FindControl("ClassEventRepeater");
        ClassEventRepeater.DataSource = moduleEvents;
        ClassEventRepeater.DataBind();
    }

    protected void ClassEventRepeater_ItemCreated(object sender, RepeaterItemEventArgs e)
    {


        if (moduleEvents != null && moduleEvents.Count > 0)
        {
            TimetableEvent classEvent = moduleEvents.ElementAt(e.Item.ItemIndex);

            if (!TimeUtils.isTimetableEventNew(classEvent))
            {
                CheckBox classEventReservedCheckbox = (CheckBox)e.Item.FindControl("ClassEventReserved");
                classEventReservedCheckbox.Checked = true;
            }

            Literal classEventTypeNameLiteral = (Literal)e.Item.FindControl("ClassEventTypeNameLiteral");
            classEventTypeNameLiteral.Text = classEvent.ModuleEvent.ModuleEventType.ModuleEventTypeName;

            HiddenField classEventTypeID = (HiddenField)e.Item.FindControl("ClassEventTypeId");
            classEventTypeID.Value = classEvent.ModuleEventId.ToString();

            if (!TimeUtils.isTimeSpanNull(classEvent.StartTime))
            {
                TextBox classEventStartTimeTextbox = (TextBox)e.Item.FindControl("ClassEventStartTimeTextbox");
                classEventStartTimeTextbox.Text = TimeUtils.convertTimespan(classEvent.StartTime);
            }
                
            if (!TimeUtils.isTimeSpanNull(classEvent.EndTime))
            {
                TextBox classEventStopTimeTextbox = (TextBox)e.Item.FindControl("ClassEventStopTimeTextbox");
                classEventStopTimeTextbox.Text = TimeUtils.convertTimespan(classEvent.EndTime);
            }


            CourseDayDropDownList courseDayDropDownList = (CourseDayDropDownList)e.Item.FindControl("CourseDayDropDownList");
            courseDayDropDownList.CourseDay = classEvent.CourseDay;
            courseDayDropDownList.reload();


            RoomDropDownList roomDropDownList = (RoomDropDownList)e.Item.FindControl("ClassEventRoomDropDown");
            roomDropDownList.SelectedRoom = classEvent.Room;
            roomDropDownList.reload();

            log.Debug("Item Created = " + classEventTypeNameLiteral.Text);


        }

    }


    private ModuleDAO moduleDAO = new ModuleDAO();

    protected void Reservation_CohortDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {

        CohortDropDownList Reservation_CohortDropDownList = (CohortDropDownList)ReservationDetailsView.FindControl("Reservation_CohortDropDownList");
        SemesterDropDownList Reservation_SemesterDropDownList = (SemesterDropDownList)ReservationDetailsView.FindControl("Reservation_SemesterDropDownList");
        ModuleDropDownList Reservation_ModuleDropDownList = (ModuleDropDownList)ReservationDetailsView.FindControl("Reservation_ModuleDropDownList");

        log.Debug("Reservation_CohortDropDownList_SelectedIndexChanged = " + Reservation_CohortDropDownList.SelectedValue);

        if (StringUtils.isValidGuid(Reservation_CohortDropDownList.SelectedValue))
        {
            Guid selectedCohortId = new Guid(Reservation_CohortDropDownList.SelectedValue);
            Reservation_ModuleDropDownList.DataSource = moduleDAO.findModulesByCohortId(selectedCohortId);
        }
        else
        {
            Reservation_ModuleDropDownList.DataSource = moduleDAO.selectAll();
        }

        // Because Ajax Update Event does not cause a non post back request
        Reservation_ModuleDropDownList.DataBind();
        DropDownUtils.addDefaultLabel(Reservation_ModuleDropDownList, "Select A Module");


//        ReservationEditingPanel.Update();
    }

    private ModuleEventDAO moduleEventDAO = new ModuleEventDAO();

    protected void Reservation_ModuleDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {
        CohortDropDownList Reservation_CohortDropDownList = (CohortDropDownList)ReservationDetailsView.FindControl("Reservation_CohortDropDownList");
        SemesterDropDownList Reservation_SemesterDropDownList = (SemesterDropDownList)ReservationDetailsView.FindControl("Reservation_SemesterDropDownList");
        ModuleDropDownList Reservation_ModuleDropDownList = (ModuleDropDownList)ReservationDetailsView.FindControl("Reservation_ModuleDropDownList");

        log.Debug("Reservation_ModuleDropDownList_SelectedIndexChanged =" + Reservation_ModuleDropDownList.SelectedValue);
        moduleEvents = timetableEventDAO.findTimetableEventsByModuleId(new Guid(Reservation_ModuleDropDownList.SelectedValue));

        log.Debug("Events found = " + moduleEvents.Count);
        Repeater ClassEventRepeater = (Repeater)ReservationDetailsView.FindControl("ClassEventRepeater");
        ClassEventRepeater.DataSource = moduleEvents;
        ClassEventRepeater.DataBind();


        //ReservationEditingPanel.Update();
    }

    private TimetableEventTypeDAO timetableEventTypeDao = new TimetableEventTypeDAO();


    protected void SaveReservations(object sender, EventArgs e)
    {
        CohortDropDownList Reservation_CohortDropDownList = (CohortDropDownList)ReservationDetailsView.FindControl("Reservation_CohortDropDownList");
        SemesterDropDownList Reservation_SemesterDropDownList = (SemesterDropDownList)ReservationDetailsView.FindControl("Reservation_SemesterDropDownList");
        ModuleDropDownList Reservation_ModuleDropDownList = (ModuleDropDownList)ReservationDetailsView.FindControl("Reservation_ModuleDropDownList");

        Repeater ClassEventRepeater = (Repeater)ReservationDetailsView.FindControl("ClassEventRepeater");

        log.Debug("Save Reservation = " + ClassEventRepeater.Items.Count);

        foreach (RepeaterItem item in ClassEventRepeater.Items)
        {
            CheckBox classEventReserved = (CheckBox)item.FindControl("ClassEventReserved");

            if (classEventReserved.Checked)
            {

                HiddenField classEventId = (HiddenField)item.FindControl("ClassEventId");
                HiddenField classEventTypeId = (HiddenField)item.FindControl("ClassEventTypeId");

                TextBox startTime = (TextBox)item.FindControl("ClassEventStartTimeTextbox");
                TextBox endTime = (TextBox)item.FindControl("ClassEventStopTimeTextbox");
                DropDownList courseDay = (DropDownList)item.FindControl("CourseDayDropDownList");
                DropDownList room = (DropDownList)item.FindControl("ClassEventRoomDropDown");


                TimetableEvent timetableEventToUpdate = timetableEventDAO.findById(new Guid(classEventId.Value));

                if (timetableEventToUpdate==null)  //adding
                {
                    timetableEventToUpdate = new TimetableEvent();

                    timetableEventToUpdate.Cohort = new CohortDAO().findById(new Guid(Reservation_CohortDropDownList.SelectedValue));
                    timetableEventToUpdate.Semester = new SemesterDAO().findById(new Guid(Reservation_SemesterDropDownList.SelectedValue));
                    timetableEventToUpdate.Module = moduleDAO.findById(new Guid(Reservation_ModuleDropDownList.SelectedValue));

                    log.Debug("Class Event Type Id = " + classEventTypeId.Value);
                    timetableEventToUpdate.ModuleEvent = moduleEventDAO.findById(new Guid(classEventTypeId.Value));

                    log.Debug("Module Event Id = " + timetableEventToUpdate.ModuleEventId);


                    String timeString = TimeUtils.adjustTimeString(startTime.Text.Trim());
                    timetableEventToUpdate.StartTime = TimeSpan.Parse(timeString);
                    timeString = TimeUtils.adjustTimeString(endTime.Text.Trim());
                    timetableEventToUpdate.EndTime = TimeSpan.Parse(timeString);

                    timetableEventToUpdate.CourseDay = new CourseDayDAO().findById(new Guid(courseDay.SelectedItem.Value));
                    timetableEventToUpdate.Room = new RoomDAO().findById(new Guid(room.SelectedItem.Value));
                    timetableEventToUpdate.TimetableEventType = timetableEventTypeDao.getReservationEventType();

                    log.Debug("Timetable Event constructed ");
                    log.Debug("Cohort Id =" + timetableEventToUpdate.CohortId);
                    log.Debug("Semester Id = " + timetableEventToUpdate.SemesterId);
                    log.Debug("Module Id = " + timetableEventToUpdate.ModuleId);
                    log.Debug("ModuleEvent Id = " + timetableEventToUpdate.ModuleEventId);
                    log.Debug("Start Time = " + timetableEventToUpdate.StartTime);
                    log.Debug("End Time = " + timetableEventToUpdate.EndTime);
                    log.Debug("CourseDay Id =" + timetableEventToUpdate.CourseDayId);
                    log.Debug("Room Id = " + timetableEventToUpdate.RoomId);
                    log.Debug("TimetableEventType Id = " + timetableEventToUpdate.TimetableEventTypeId);
                    timetableEventToUpdate.TimetableEventId = Guid.NewGuid();
                    log.Debug("TimetableEventId = " + timetableEventToUpdate.TimetableEventId);

                    timetableEventDAO.insert(timetableEventToUpdate);
                    log.Debug("Inserting Reservation");

                }
                else
                {

                    timetableEventToUpdate.Cohort = new CohortDAO().findById(new Guid(Reservation_CohortDropDownList.SelectedValue));
                    timetableEventToUpdate.Semester = new SemesterDAO().findById(new Guid(Reservation_SemesterDropDownList.SelectedValue));
                    timetableEventToUpdate.Module = moduleDAO.findById(new Guid(Reservation_ModuleDropDownList.SelectedValue));

                    timetableEventToUpdate.ModuleEvent = moduleEventDAO.findById(new Guid(classEventTypeId.Value));

                    String timeString = TimeUtils.adjustTimeString(startTime.Text.Trim());
                    timetableEventToUpdate.StartTime = TimeSpan.Parse(timeString);
                    timeString = TimeUtils.adjustTimeString(endTime.Text.Trim());
                    timetableEventToUpdate.EndTime = TimeSpan.Parse(timeString);

                    timetableEventToUpdate.CourseDay = new CourseDayDAO().findById(new Guid(courseDay.SelectedItem.Value));
                    timetableEventToUpdate.Room = new RoomDAO().findById(new Guid(room.SelectedItem.Value));
                    timetableEventToUpdate.TimetableEventType = timetableEventTypeDao.getReservationEventType();

                    timetableEventDAO.save(timetableEventToUpdate);
                    log.Debug("Updating Reservation");
                    
                }

                

            }
        }
    }

    protected void BackButton_Click(object sender, EventArgs e)
    {

        ReservationEditingPanel.Visible = false;
        ReservationViewPanel.Visible = true;
    }


}
